package com.htdata.iiot.tools;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;

import org.apache.log4j.Logger;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MqttEntity implements MqttCallback {
	private Logger logger = Logger.getLogger(MqttEntity.class);

	private String clientId;
	private MqttClient mqttClient;


	public MqttEntity() {
		this.clientId = "ClientGUI79_0";
	}

	public MqttEntity(String clientId) {
		this.clientId = clientId;

	}
	public MqttClient mqttConnect(String url) throws UnsupportedEncodingException, URISyntaxException {

		boolean connectStatue = false;
		int connectNum = 2;

		try {
			mqttClient = new MqttClient("tcp://" + url, clientId);

			while (!connectStatue && (connectNum > 0) && (mqttClient != null)) {
				connectStatue = connect();
				connectNum--;
			}
			if (connectStatue) {
				logger.info("connect to mqtt successfully");
				return mqttClient;
			} else {
				logger.error("connect to mqtt failed");
				if (mqttClient != null) {
					mqttClient.close();
				}
			}
		} catch (MqttException e) {
			logger.warn("create MqttClient failed! " + e.getMessage());
		}
		return null;
	}

	public boolean connect() throws UnsupportedEncodingException, URISyntaxException {
		String[] mqttBrokerArray = {mqttClient.getServerURI()};
		// System.out.println(mqttBrokerArray[0]);
		// mqttBrokerArray[0] = "tcp://192.168.0.79:1883";
		MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
		mqttConnectOptions.setServerURIs(mqttBrokerArray);
		mqttConnectOptions.setAutomaticReconnect(true);

		mqttConnectOptions.setUserName("wly");
		mqttConnectOptions.setPassword("wly".toCharArray());

		mqttConnectOptions.setCleanSession(false);

		mqttConnectOptions.setMaxInflight(100);

		try {
			mqttClient.setCallback(this);
			mqttClient.connect(mqttConnectOptions);
		} catch (Exception e) {
			logger.warn(e.getMessage());
			return false;
		}

		return true;
	}

	public MqttClient getMqttClient() {
		return this.mqttClient;
	}

	@Override
	public void connectionLost(Throwable cause) {
		logger.warn("connectionLost cause:" + cause.getMessage());
		try {
			connect();
		} catch (UnsupportedEncodingException | URISyntaxException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void messageArrived(String topic, MqttMessage message) throws Exception {
	}

	@Override
	public void deliveryComplete(IMqttDeliveryToken token) {
	}
}
